package com.example.springboot.exception;

import com.example.springboot.vo.ResVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * controller 增强器
 *
 * @author sam
 * @since 2017/7/17
 */
@ControllerAdvice
@Slf4j
public class MyControllerAdvice {
    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResVO<String> errorHandler(Exception ex) {

//		自定义异常
        if (ex instanceof NotLoginException) {
            NotLoginException notLoginException = (NotLoginException) ex;
            log.error("Exception 异常", ex);
            String message = ex.getMessage();
            return new ResVO<String>(((NotLoginException) ex).getStatus(), ex.getMessage(), "");

        }
        log.error("Exception 异常", ex);
        // NotFoundException
        return new ResVO<>(5001, "服务器繁忙，请稍后重试", "");
    }

    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public String myErrorHandler(NullPointerException ex) {
        return "空指针异常";
    }

    @ResponseBody
    @ExceptionHandler(value = NotFoundException.class)
    public ResVO<String> notFoundException(NotFoundException ex) {
        log.error("异常类信息", ex);
        String message = ex.getMessage();
        return new ResVO<>(ex.getStatus(), ex.getMessage(), "");
    }

}
